<template>
  <!-- 绑定FBA货件-->
  <a-modal :width="1200" v-model:visible="showBindDialog" title="绑定FBA货件" title-align="start" :mask-closable="false" ok-text="确认绑定" cancel-text="取消绑定" :ok-loading="submitLoading" @cancel="closedDialog" :on-before-ok="submitData">
    <div class="flex bind-w">
      <div class="left-w">
        <div class="info-item">
          <span class="label">发货单号：</span>
          <span>{{ currentData.billNo }}</span>
        </div>
        <div class="info-item">
          <span class="label">发货仓：</span>
          <span>{{ currentData.warehouseName }}</span>
        </div>
        <div class="info-item">
          <span class="label">发货地址：</span>
          <span>{{ getAddress(currentData.shipFromAddress) }}</span>
        </div>
        <div class="info-item">
          <span class="label">店铺：</span>
          <span>{{ currentData.shopName }}</span>
        </div>
        <div class="info-item">
          <span class="label">FBA货件号：</span>
          <!-- FBA170MRFRBH -->
          <a-input v-model="shipmentId" style="width: 160px" size="small" placeholder="请输入SKU" allow-clear />
          <a-button size="small" style="margin-left: 5px" @click="getAmaFbaDetail">获取</a-button>
        </div>
        <div class="info-item">
          <span class="label">货件名称：</span>
          <span>{{ amaFbaDetail.shipmentName }}</span>
        </div>
        <div class="info-item">
          <span class="label">CenterId：</span>
          <span>{{ amaFbaDetail.destinationFulfillmentCenterId }}</span>
        </div>
        <div class="info-item">
          <span class="label">状态：</span>
          <span>{{ amaFbaDetail.shipmentStatus }}</span>
        </div>
        <div class="info-item">
          <span class="label">贴标方：</span>
          <span>{{ amaFbaDetail.labelPrepType == 'SELLER_LABEL' ? '卖家' : '买家' }}</span>
        </div>
        <div class="info-item">
          <span class="label">包装方式：</span>
          <span>{{ amaFbaDetail.boxContentsSource }}</span>
        </div>
        <div class="info-item">
          <span class="label">收货地址：</span>
          <span>{{ getAddress(amaFbaDetail.shipToAddress) }}</span>
        </div>
        <div class="handle-w">
          <p class="warningColor">您可以下载该发货单数据，前往亚马逊后台，通过导入文件的方式，创建FBA货件！</p>
          <a-button @click="downloadFba">下载发货单数据</a-button>
        </div>
      </div>
      <div class="right-w">
        <a-alert type="warning" style="margin-right: 10px" v-if="showResult && !amaFbaDetail.shipmentId">抱歉，FBA发货单信息获取失败，请确认货件号是否输入正确！</a-alert>
        <div class="table-w">
          <div class="table-item" style="margin-right: 5px">
            <p class="title">FBA货件单明细</p>
            <a-table class="table-singe-line" :loading="getLoading" :data="fbaItems" size="mini" :bordered="false" :pagination="false">
              <template #columns>
                <a-table-column data-index="img" title="图片" :width="60">
                  <template #cell="{ record }">
                    <ImgPopover :src="record.productImg">
                      <template #con>
                        <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                      </template>
                    </ImgPopover>
                  </template>
                </a-table-column>
                <a-table-column data-index="sellerSKU" title="MSKU" :width="100" />
                <a-table-column data-index="fulfillmentNetworkSKU" title="FNSKU" :width="100" />
                <a-table-column data-index="quantityShipped" title="数量" :width="60" />
                <a-table-column title="提示" :width="80">
                  <template #cell="{ record }">
                    <p v-if="record.state == 1" class="warningColor"><icon-exclamation-circle />未匹配到</p>
                    <p v-if="record.state == 2">数量不对</p>
                    <p v-if="record.state == 3"><icon-check style="color: rgb(var(--success-6)); font-size: 16px" /></p>
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </div>
          <div class="table-item">
            <p class="title">发货单明细</p>
            <a-table class="table-singe-line" :data="skuDetails" size="mini" :bordered="false" :pagination="false">
              <template #columns>
                <a-table-column data-index="img" title="图片" :width="60">
                  <template #cell="{ record }">
                    <ImgPopover :src="record.productImg">
                      <template #con>
                        <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                      </template>
                    </ImgPopover>
                  </template>
                </a-table-column>
                <a-table-column title="MSKU/FNSKU" :width="100">
                  <template #cell="{ record }">
                    <TextLimit :rows="1">{{ record.msku }}</TextLimit>
                    <TextLimit :rows="1">{{ record.fnsku }}</TextLimit>
                  </template>
                </a-table-column>
                <a-table-column data-index="sku" title="SKU" :width="100">
                  <template #cell="{ record }">
                    <ShowSpuDetailBySku :val="record.sku" :showLimit="false" />
                  </template>
                </a-table-column>
                <a-table-column data-index="realNum" title="数量" :width="60" />
                <a-table-column title="提示" :width="80">
                  <template #cell="{ record }">
                    <p v-if="record.state == 1" class="warningColor"><icon-exclamation-circle />未匹配到</p>
                    <p v-if="record.state == 2">数量不对</p>
                    <p v-if="record.state == 3"><icon-check style="color: rgb(var(--success-6)); font-size: 16px" /></p>
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getAmazonFbaShipment, getAmazonFbaShipmentItems, bindFbaShipmentByStore, bindFbaShipmentBySale, downloadFbaShipmentMskuData } from '@/api/purchase'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentData: {
      type: Object,
      default: () => {},
    },
    source: {
      type: String,
      default: 'store',
    },
  })

  const showBindDialog = ref(props.isShow)
  const submitLoading = ref(false)
  const getLoading = ref(false)
  const shipmentId = ref()
  const showResult = ref(false)
  const fbaItems = ref<Array<any>>([])
  const amaFbaDetail = ref<any>({})
  const skuDetails = ref<any>(JSON.parse(JSON.stringify(props.currentData.skuDetails)))

  // 获取亚马逊货件信息
  async function getAmaFbaDetail() {
    // if (!shipmentId.value) return
    fbaItems.value = []
    amaFbaDetail.value = {}
    showResult.value = false
    getLoading.value = true
    const res: any = await getAmazonFbaShipment({
      id: props.currentData.id,
      shipmentId: shipmentId.value,
      // id: '64e57ad4b4823c2658f3d897',
      // shipmentId: 'FBA170MRFRBH',
    })
    getLoading.value = false
    if (res?.data) {
      showResult.value = true
      amaFbaDetail.value = res.data
      getAmaFbaItems()
    }
  }
  // 获取亚马逊货件明细
  async function getAmaFbaItems() {
    getLoading.value = true
    const res: any = await getAmazonFbaShipmentItems({
      id: props.currentData.id,
      shipmentId: shipmentId.value,
      // id: '64e57ad4b4823c2658f3d897',
      // shipmentId: 'FBA170MRFRBH',
    })
    getLoading.value = false
    fbaItems.value = res?.data || []
    matchItem()
  }
  // 匹配明细
  async function matchItem() {
    // 发货单明细匹配
    skuDetails.value.forEach((el: any) => {
      let currentRow = fbaItems.value.find((item: any) => item.sellerSKU === el.msku)
      if (!currentRow) {
        el.state = 1
      } else if (currentRow.quantityShipped != el.realNum) {
        el.state = 2
      } else {
        el.state = 3
      }
    })
    // FBA货件明细
    fbaItems.value.forEach((el: any) => {
      let currentRow = skuDetails.value.find((item: any) => el.sellerSKU === item.msku)
      if (!currentRow) {
        el.state = 1
      } else if (el.quantityShipped != currentRow.realNum) {
        el.state = 2
      } else {
        el.state = 3
      }
    })
  }
  // 显示地址
  function getAddress(address: any) {
    return `${address?.countryCode || ''}${address?.stateOrProvinceCode || ''}${address?.city || ''}${address?.addressLine1 || ''}`
  }

  // 开始绑定
  async function submitData() {
    if (skuDetails.value.some((el: any) => el.state != 3) || fbaItems.value.some((el: any) => el.state != 3)) {
      Message.error('存在不匹配的明细')
      return false
    }
    let apiMethod = props.source == 'store' ? bindFbaShipmentByStore : bindFbaShipmentBySale

    const res: any = await apiMethod({
      id: props.currentData.id,
      amzStatus: amaFbaDetail.value.shipmentStatus,
      boxContentsSource: amaFbaDetail.value.boxContentsSource,
      centerId: amaFbaDetail.value.destinationFulfillmentCenterId,
      labelPrepType: amaFbaDetail.value.labelPrepType,
      shipmentId: amaFbaDetail.value.shipmentId,
      shipmentName: amaFbaDetail.value.shipmentName,
    })
    if (!res) return false
    Message.success('绑定成功')
    emit('success')
    emit('closed')
  }
  // 下载FBA数据
  async function downloadFba() {
    const res: any = await downloadFbaShipmentMskuData({ id: props.currentData.id })
    if (res) {
      let blob = new Blob([res.data], { type: 'application/octet-stream' })
      const $link = document.createElement('a')
      $link.href = URL.createObjectURL(blob)
      $link.download = `FBA发货单.xlsx`
      $link.click()
    }
  }
  // 关闭
  function closedDialog() {
    showBindDialog.value = false
    emit('closed')
  }
</script>
<style lang="less" scoped>
  .bind-w {
    height: calc(84vh - 160px);
    .left-w {
      width: 300px;
      padding-right: 10px;
      flex-shrink: 0;
      .info-item {
        display: flex;
        margin-bottom: 10px;
      }
      .label {
        width: 90px;
        text-align: right;
        flex-shrink: 0;
        color: #666;
      }
      .handle-w {
        margin-top: 40px;
        .warningColor {
          font-size: 12px;
          margin-bottom: 5px;
        }
      }
    }
    .right-w {
      flex: 1;
      .table-w {
        height: calc(100% - 50px);
        display: flex;
        .table-item {
          flex: 1;
          border: 1px solid #eee;
          flex-shrink: 0;
          .title {
            font-weight: bold;
            text-align: center;
            padding: 5px 0;
          }
        }
      }
    }
  }
</style>
